<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>精简入库</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<link rel="stylesheet" media="all" href="${pageContext.request.contextPath }/assets/formSelects/formSelects-v4.css">
	<style type="text/css">
		#head td{
			width: 300px
		}
	</style>
</head>
<script type="text/javascript">
	$(document).on('keydown','[lay-id="materiel_list"] .layui-table-edit',function(e){
		var td = $(this).parent('td'),
		tr = td.parent('tr'),
		trs = tr.parent().parent().find('tr'),
		tr_index = tr.index(),
		td_index = td.index(),
		td_last_index = tr.find('[data-edit="text"]:last').index(),
		td_first_index = tr.find('[data-edit="text"]:first').index();
		switch(e.keyCode){
			case 13:
				 return false;
				 break;
			case 39:
				td.nextAll('[data-edit="text"]:first').click();
				if(td_index == td_last_index){
					tr.next().find('td').eq(td_first_index).click();
					if(tr_index == trs.length-1){
						trs.eq(0).find('td').eq(td_first_index).click();
					}
				}
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
			case 37:
				td.prevAll('[data-edit="text"]:first').click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
			case 38:
				tr.prev().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
			case 40:
				tr.next().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
		} 
	})
</script>
<body class="layui-anim layui-anim-up">
<div class="x-nav">
	<span class="layui-breadcrumb">
 			<a href="">首页</a>
		<a>
			<cite>精简入库</cite>
		</a>
	</span>
   </div>
<div class="x-body">
	<input type="hidden" id="cid" name="cid"  value="${cid}" >
	<div class="layui-row">
		<div class="layui-form">
			<div class="layui-input-inline">

				<td>
						<input type="text" name="keyword" id="keyword" readonly value="${cname}"   style="display: inline; width: 180px; margin-left: 10px" class="layui-input ">
				</td>
<td>
					<input class="layui-input" id="khnum" placeholder="请输入客户单号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
				</td>
				<div class="layui-input-inline">
					<%-- <select style="width: 285px" class="" name="keyword" id="keyword" lay-filter="keyword">
						<option value="">--请选择供应商--</option>
						<c:forEach items="${allCustomerList }" var="customer">
							<option value="${customer.id}">${customer.customer_name }</option>
						</c:forEach>
					</select> --%>
					  <input class="layui-input" readonly name="sendCompany" id="sendCompanyc1" value="${cname}"autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
				</div>

				<div class="layui-input-inline">
					<select id="selectState" name="selectState" style="width: 285px">
						<option value="">--请选择--</option>
						<option value="1">已收货</option>
						<option value="0">未收货</option>
					</select>
				</div>
				<!-- <div class="layui-input-inline">
					<select id="selectType" name="selectType" style="width: 285px">
						<option value="">请选择类型</option>
						<option value="0">正常入库</option>
						<option value="1">发货退回</option>
					</select>
				</div> -->
				<div class="layui-input-inline">
					<input class="layui-input" id="startTime" placeholder="请输入开始时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					-<input class="layui-input" id="endTime" placeholder="请输入结束时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px"> 
				</div>

				<div class="layui-input-inline">
					<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>		</div>
			 <button class="layui-btn layui-btn-danger" id="export"><i class="layui-icon layui-icon-upload"></i>导出</button> </div>

		</div>
	</div>

	<script type="text/html" id="toolbarDemo">
		<div class="layui-btn-container">
			<button class="layui-btn layui-btn-warm" lay-event="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
			<button class="layui-btn layui-btn-danger" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
			<button class="layui-btn" lay-event="confirm"><i class="layui-icon layui-icon-ok"></i>确认入库</button>
		</div>
	</script>
	<table class="layui-hide" id="test" lay-filter="test"></table>
	<script type="text/html" id="barDemo">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit">编辑</i></a>
		<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete">删除</i></a>
	</script>
	<script type="text/html" id="barDemo2">
		<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete">删除</i></a>
	</script>
	
	<div id = "details">
			<table class="layui-hide" id="simplificationInDetails" lay-filter="simplificationInDetails"></table>
		</div>
</div>

<!-- 弹框 -->
<div id="formDiv" hidden>
	<div class="box">
		<form class="layui-form layui-card-body" id="addform">
			<table style="border: none;">
				<tbody id="head">
					<tr>
						<td>
							<span>入库单号&emsp;</span>
							<div class="layui-inline" style="width:65%;">
								<input class="layui-input layui-inline" name="receiveNumber" readonly="readonly" id="receiveNumber" lay-filter="receiveNumber"/>
							</div>
						</td>
						<td>
							<span>供应商&emsp;</span>
							<div class="layui-inline" style="width:65%">
								 <input class="layui-input" name="sen" id="sen" value="${cname}" autocomplete="off" > 
					 
						 	<input type="hidden" name="sendCompany" id="sendCompany1"  value="${cid}" >
							</div>
							<div class="layui-inline" style="float: right;margin-right: 1em;margin-top: 10px;">
								<font style="color:red; font-size: 24px;">*</font>
							</div>
						</td>
						<td>
							<span>发货人&emsp;</span>
							<div class="layui-inline" style="width:70%;">
								<input class="layui-input layui-inline" name="sendName" readonly="readonly" value="${lname}" id="sendName" lay-filter="sendName"/>
							</div>
						</td>
					</tr>
					<tr style="height: 10px"></tr>
					<tr>
						<td>
							<span>日&emsp;&emsp;期&emsp;</span>
							<div class="layui-inline" style="width:65%">
								<input class="layui-input layui-inline" name="createDate" id="createDate" lay-filter="createDate"/>
							</div>
							<div class="layui-inline" style="float: right;margin-right: 1em;margin-top: 10px;">
								<font style="color:red; font-size: 24px;">*</font>
							</div>
						</td>
						<td>
							<span>收货人&emsp;</span>
							<div class="layui-inline" style="width:65%;">
								<input class="layui-input layui-inline"  value="${charger}" name="rName" readonly="readonly" id="rName" lay-filter="sendName"/>
							</div>
						</td>
						<td>
							<span>收货人电话&emsp;</span>
							<div class="layui-inline" style="width:60%;">
								<input class="layui-input layui-inline" name="rtel"  value="${chargertel}" readonly="readonly" id="rtel" lay-filter="sendName"/>
							</div>
						</td>
						</tr>
					<tr>
					<td>
							<span>客户单号&emsp;</span>
							<div class="layui-inline" style="width:65%;">
								<input class="layui-input layui-inline" name="sendNumber"  id="sendNumber" lay-filter="sendName"/>
							</div>
						</td>
						<td>
							<span>类&emsp;&emsp;&emsp;型&emsp;</span>
							<div class="layui-inline" style="width:60%">
								<select class="" name="type" id="type">
									<option value="0">正常入库</option>
									<option value="1">发货退回</option>
								</select>
							</div>
						</td>
					</tr>
					<tr style="height: 10px"></tr>
					<tr>
						<!-- <td>
							<input type="button" class="layui-btn layui-btn-normal" style="margin-top: 10px; margin-left: 74px" onclick="addProduct()" value="选择物料">
						</td>
						<td></td> -->
						<td colspan="3" align="right">
							<input type="button" class="layui-btn layui-btn-normal" onclick="addProduct()" value="选择物料" style="margin-right: 35px;">
						</td>
					</tr>
				</tbody>
			</table>
			<table class="layui-hide" id="materiel_list" lay-filter="materiel_list"></table>
			<div class="layui-form-item" style="margin-left: 250px">
				<div class="layui-input-block">
					<input type="button" class="layui-btn layui-btn-blue" lay-submit lay-filter="addform" id="subform" value="确定">
					<button class="layui-btn layui-btn-primary" style="margin-left:120px">取消</button>
				</div>
			</div>
		</form>
	</div>
</div>
<!-- 产品选择框 -->
<div id="productDiv" hidden="hidden">
	<form class="layui-form" onsubmit="return false">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<!-- <td>
							<input class="layui-input" name="materiel_name" id="materiel_name" placeholder="请输入中文名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td> -->
						<td>
							<input class="layui-input" name="materiel_num" id="materiel_num" placeholder="请输入SAP/PAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			&emsp;<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" data-type="reload2"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
		<table id="productTable" lay-filter="productTable"></table>
		<xblock>
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>
		</xblock>
	</form>
</div>
<script>
layui.use(['table','layer','upload','form','laydate'], function(){
	var table = layui.table;
	var layer = layui.layer,
    form = layui.form,
    laydate = layui.laydate
    
    //日期时间范围
	var minListDate = "1000-01-01 00:00:00";//最小可选时间，例：1990-02-01
    var maxListDate = "3000-12-31 23:59:59";//最大可选时间，例：2200-12-31   
    var enddate = laydate.render({
        elem: "#endTime",
        format: 'yyyy-MM-dd HH:mm:ss',
        type: 'datetime',
        min: minListDate,
        max: maxListDate,
        done: function (val, date) {
            if (date && date.year){
            	//设置结束时间 设置开始时间的最大值为结束时间
                begindate.config.max = {
                    year: date.year,
                    month: date.month - 1,//必须减1才是正确值
                    date: date.date,
                    hours: date.hours,
                    minutes: date.minutes,
                    seconds: date.seconds
                };
            }else {
            	//清除结束值    设置开始时间最大值
                var dateInit = new Date(maxListDate.replace(/-/g, "/"));
                begindate.config.max = {
                    year: dateInit.getFullYear(),
                    month: dateInit.getMonth(),
                    date: dateInit.getDate(),
                    hours: dateInit.getHours(),
                    minutes: dateInit.getMinutes(),
                    seconds: dateInit.getSeconds()
                };
            }
        }
    });
    var begindate = laydate.render({
        elem: "#startTime",
        format: 'yyyy-MM-dd HH:mm:ss',
        type: 'datetime',
        min: minListDate,
        max: maxListDate,
        done: function (val, date) {
            if (date && date.year){
            	//设置开始时间 设置结束时间的最小值为开始时间
                enddate.config.min = {
                    year: date.year,
                    month: date.month - 1,
                    date: date.date,
                    hours: date.hours,
                    minutes: date.minutes,
                    seconds: date.seconds
                };
            }else {
            	//清除开始值 ，设置结束值最小值
                var dateInit = new Date(minListDate.replace(/-/g, "/"));
                enddate.config.min = {
                    year: dateInit.getFullYear(),
                    month: dateInit.getMonth(),
                    date: dateInit.getDate(),
                    hours: dateInit.getHours(),
                    minutes: dateInit.getMinutes(),
                    seconds: dateInit.getSeconds()
                };
            }
        }
    });
    
	var $ = layui.jquery, active = {
			reload:function () {
				var keyword = $("#cid").val();

				var selectState = $("#selectState").val();


				if(keyword == "" && selectState == ""){
					var strWhere = "r.isSimple = 1 and ";
				}else {

					if (keyword == "") {

						var strWhere = "r.isSimple = 1 and state = "+selectState+" and ";
					}else if (selectState == "") {

						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and ";
					}else {
						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and state = "+selectState+" and ";
					}
				}
				
				var receiveNumber = $.trim($("#receiveNumberc").val());
				if(receiveNumber != null && receiveNumber != ""){
					var strWhere = strWhere + " receive_number = '"+receiveNumber+"' and ";
				}
				var sendNumber = $.trim($("#khnum").val());
				if(sendNumber != null && sendNumber != ""){
					var strWhere = strWhere + " send_number = '"+sendNumber+"' and ";
				}
				var startTime = $.trim($("#startTime").val());
				if(startTime != null && startTime != ""){
					var strWhere = strWhere + " create_date >= '"+startTime+"' and ";
				}
				var endTime = $.trim($("#endTime").val());
				if(endTime != null && endTime != ""){
					var strWhere = strWhere + " create_date <= '"+endTime+"' and ";
				}
				var selectType = $.trim($("#selectType").val());
				if(selectType != null && selectType != ""){
					var strWhere = strWhere + " r.type = '"+selectType+"' and ";
				}
				table.reload('contenttable',{
					method:'get',
					where:{"strWhere": strWhere}
					,page: {
	                    curr: 1//重新从第 1 页开始
	                }
				});
			},
			reload2:function () {
				var materiel_name=$('#materiel_name').val();
	    		var materiel_num=$('#materiel_num').val();
	    		var table = layui.table;
		 		var verify = /^[0-9,-]*$/;
				//if(verify.test(materiel_num)){
					var split = materiel_num.split(',')
					if(split.length <= 5){
						table.reload('contenttable2',{
							method:'post'
							,where:{"materielName":materiel_name,"materielNum":materiel_num}
			         		/* ,page: {
			                    curr: 1//重新从第 1 页开始
			                } */
						});
					}else{
						layer.msg("最多可同时查5个！");
					}
				/* }else{
					layer.msg("只能输入数字和英文逗号！");
				} */
			}
		}
	$('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
	var keyword = $("#cid").val();
	var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and ";
	table.render({
	    elem: '#test'
	    ,where:{"strWhere": strWhere}
	    ,url:'${pageContext.request.contextPath }/simplificationIn/selectSimplificationInList.do'
	    ,title: '入库单列表'
	    ,toolbar: '#toolbarDemo'
	    ,id :'contenttable'
	    ,limits:[10,20,30]
	    ,cols: [[
			{type: 'checkbox', fixed: 'left'}
	      	,{field:'', title:'序号', sort: true, type:'numbers', width: 60}
	      	,{field:'receiveNumber', title:'入库单号'}
	      	,{field:'sendCompany', title:'供应商'}
	      	,{field:'createDate', title:'发货日期'
	      		,
            	templet: function(d){
            		return changeDateFormat(d.createDate)
            }
			}
	      	,{field:'sendName', title:'发货人'}
	      	,{field:'createName', title:'创建人'}
	    	,{field:'sendNumber', title:'客户单号'}
	      	,{field:'state', title:'订单状态'
	      		,templet: function(d){
                    var value = d.state;
                    if(value == 0){
                        value = "未收货"
                    }else if(value == 1){
                        value = "已收货"
                    }
                    return value;
                }	
	      	}
	      	/* ,{field: 'type',title: '类型',align:'center'
                ,templet: function(d){
                    var value = d.type;
                    if(value == 0){
                        value = "正常入库"
                    } else if (value == 1){
                        value = "发货退回"
                    }
                    return value;
                }
            } */
	      	/* ,{fixed: 'right', title:'操作', toolbar: '#barDemo'} */
	    ]]
	    ,page: true
	    ,done:function(){
	    	$('th').css({
                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
            })
	    }
	});
	table.render({
        elem: '#materiel_list'
        ,defaultToolbar:['filter', 'print']
        ,cols: [[
            {type: 'checkbox',fixed: 'left'},
            {field:'', title:'序号', width: 50,type:'numbers', align:'center'},
            {field:'id', title:'id', align:'center', hide:true},
            {field:'mid', title:'mid', align:'center', hide:true},
            {field:'materiel_name', title:'中文名称', align:'center'},
            {field:'materiel_num', title:'SAP/PAD', align:'center'},
            {field:'packing_quantity', title:'包装数量', align:'center'},
            {field:'outgoing_frequency', title:'出库频率', align:'center'},
         {field:'pici', title:'<span style="color: red">批次</span>', edit: 'text', align:'center'}, 
            {field:'totalNum', title:'<span style="color: red">发货良品数</span>', edit: 'text', align:'center'},
            {field:'ngNum', title:'<span style="color: red">发货不良品数</span>', edit: 'text', align:'center'},
            ,{fixed: 'right', title:'操作', toolbar: '#barDemo2'}
        ]]
        ,limit:Number.MAX_VALUE
        ,page: false
        ,height: 400
        ,done : function(){
            $('th').css({
                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
            })
        }
    });
	
	table.on('row(test)', function(obj){
        var data = obj.data;
        table.render({
            elem: '#simplificationInDetails'
            ,url:'${pageContext.request.contextPath }/receiveDetail/list.do?receiveNumber='+data.receiveNumber
            ,toolbar: '#Detailtoolbar'
            ,title: '明细表'
            ,limits:[10,20,30]
            //,defaultToolbar:['filter', 'print']
            ,cols: [[
                {type: 'checkbox',fixed: 'left'},
                {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                {field:'mid', title:'物料id', align:'center', hide:true},
                {field:'materiel_name', title:'物料名称', align:'center'},
                {field:'materiel_num', title:'SAP/QAD', align:'center'},
                {field:'packing_quantity', title:'包装数量', align:'center'},
                {field:'pici', title:'批次', align:'center'}, 
                {field:'totalNum', title:'发货良品数(个)', align:'center'},
                {field:'ngNum', title:'发货不良品数(个)', align:'center'},
                {field:'codeNum', title:'收货良品数(个)', align:'center'},
                {field:'ngNum', title:'收货不良品数(个)', align:'center'},
            ]]
            ,page: true
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
    });
	//监听复选框事件
	table.on('checkbox(test)',function(obj){
		if(obj.checked == true && obj.type == 'all'){ 
			//点击全选 
			$('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click'); 
		}else if(obj.checked == false && obj.type == 'all'){ 
			//点击全不选 
			$('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click'); 
		}else if(obj.checked == true && obj.type == 'one'){ 
			//点击单行
			if(obj.checked == true){ 
				obj.tr.addClass('layui-table-click'); 
			}else{ 
				obj.tr.removeClass('layui-table-click'); 
			} 
		}else if(obj.checked == false && obj.type == 'one'){ 
			//点击全选之后点击单行 
			if(obj.tr.hasClass('layui-table-click')){
				obj.tr.removeClass('layui-table-click'); 
			} 
		}
	})
	
	//单子头事件
	table.on('toolbar(test)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		switch(obj.event){
    		case 'add':
    		layer.open({
    			  type: 1 		//Page层类型
    			  ,area: ['950px', ''] //宽  高
    			  ,skin: 'alert-skin'
    			  ,title: '新增入库单'
    			  ,shade: 0.6 	//遮罩透明度
    			  ,shadeClose: true //点击遮罩关闭
    			  ,maxmin: true //允许全屏最小化
    			  ,anim: 1 		//0-6的动画形式，-1不开启
    			  ,content: $('#formDiv')
    			  ,success: function () {
    				  var timestamp = (new Date()).getTime();
                      $("#receiveNumber").val("R-"+timestamp);

                      laydate.render({
                          elem: '#createDate'
                        	  ,type: 'datetime'
                      });
                     
                      $("#createDate").val(curentTime())
                      table.reload('materiel_list',{
                          data : new Array()
                      });

                      $("#sendCompany").val("")
                      form.render();
    			  }
    			  ,end: function () {
    				  var formDiv = document.getElementById('formDiv');
    				  formDiv.style.display = '';
    			  }
    		});
    		break;
    		//批量删除
    		case 'delete':
    			var data = checkStatus.data;
	        	if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        	}else{
		        	var receiveNumber = new Array();
		        	for(var i=0;i<data.length;i++){
		        		receiveNumber[i] = data[i].receiveNumber;
		        		state = data[i].state;
		        		if(state!=0){
		        			toastr.warning("只能删除未收货的订单！");
		        		}else{
			        		layer.confirm('确定删除吗？', function(index){
			        			$.ajax({
			        		    	type:'post',
			        		    	url:'${pageContext.request.contextPath }/simplificationIn/deleteSimplificationInByNumber.do',
			        		    	data:{"receiveNumber":receiveNumber},
			        		    	success:function(data){
			        		    		if(data>0){
			        		    			toastr.success("删除成功！");
			        		    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
			        							//关闭模态框
			        							// 父页面刷新
			        		    				 layer.closeAll();
	                                        	 var keyword = $("#cid").val();

	                             				var selectState = $("#selectState").val();


	                             				if(keyword == "" && selectState == ""){
	                             					var strWhere = "r.isSimple = 1 and ";
	                             				}else {

	                             					if (keyword == "") {

	                             						var strWhere = "r.isSimple = 1 and state = "+selectState+" and ";
	                             					}else if (selectState == "") {

	                             						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and ";
	                             					}else {
	                             						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and state = "+selectState+" and ";
	                             					}


	                             				}
	                             				
	                             				var receiveNumber = $.trim($("#receiveNumberc").val());
	                             				if(receiveNumber != null && receiveNumber != ""){
	                             					var strWhere = strWhere + " receive_number = '"+receiveNumber+"' and ";
	                             				}
	                             				var sendNumber = $.trim($("#khnum").val());
	                             				if(sendNumber != null && sendNumber != ""){
	                             					var strWhere = strWhere + " send_number = '"+sendNumber+"' and ";
	                             				}
	                             				var startTime = $.trim($("#startTime").val());
	                             				if(startTime != null && startTime != ""){
	                             					var strWhere = strWhere + " create_date >= '"+startTime+"' and ";
	                             				}
	                             				var endTime = $.trim($("#endTime").val());
	                             				if(endTime != null && endTime != ""){
	                             					var strWhere = strWhere + " create_date <= '"+endTime+"' and ";
	                             				}

	                             				table.reload('contenttable',{
	                             					method:'get',
	                             					where:{"strWhere": strWhere}
	                             					,page: {
	                             	                    curr: 1//重新从第 1 页开始
	                             	                }
	                             				});
			        						},2000);
			        		    		}else{
			        		    			toastr.warning("删除失败！");
			        		    		}
			        		    	}
		
			        		    })
			        		    layer.close(index);
			        		})
		        		}
		        	}
	        	}
    		break;
    		case 'confirm':
    			var data = checkStatus.data;
    			if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        	}else{
	    			var receiveNumber = data[0].receiveNumber;
	    			if(data[0].state == 1){
	    				toastr.warning("已收货，请不要重复操作");
	    				return;
	    			}else{
	    				$.ajax({
		   		            type:'post',
		   		            data:'receiveNumber='+receiveNumber,
		   		            url:'${pageContext.request.contextPath}/simplificationIn/submitReceipt.do',
		   		            dataType: 'JSON',
		   		            async: false,
		   		            success:function (result) {
		   		               if(result > 0) {
		   		            		toastr.success("入库成功！");
		   		            		setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	        							// 父页面刷新
		   		            		 layer.closeAll();
                                	 var keyword = $("#cid").val();

                     				var selectState = $("#selectState").val();


                     				if(keyword == "" && selectState == ""){
                     					var strWhere = "r.isSimple = 1 and ";
                     				}else {

                     					if (keyword == "") {

                     						var strWhere = "r.isSimple = 1 and state = "+selectState+" and ";
                     					}else if (selectState == "") {

                     						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and ";
                     					}else {
                     						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and state = "+selectState+" and ";
                     					}


                     				}
                     				
                     				var receiveNumber = $.trim($("#receiveNumberc").val());
                     				if(receiveNumber != null && receiveNumber != ""){
                     					var strWhere = strWhere + " receive_number = '"+receiveNumber+"' and ";
                     				}
                     				var sendNumber = $.trim($("#khnum").val());
                     				if(sendNumber != null && sendNumber != ""){
                     					var strWhere = strWhere + " send_number = '"+sendNumber+"' and ";
                     				}
                     				var startTime = $.trim($("#startTime").val());
                     				if(startTime != null && startTime != ""){
                     					var strWhere = strWhere + " create_date >= '"+startTime+"' and ";
                     				}
                     				var endTime = $.trim($("#endTime").val());
                     				if(endTime != null && endTime != ""){
                     					var strWhere = strWhere + " create_date <= '"+endTime+"' and ";
                     				}

                     				table.reload('contenttable',{
                     					method:'get',
                     					where:{"strWhere": strWhere}
                     					,page: {
                     	                    curr: 1//重新从第 1 页开始
                     	                }
                     				});
	        						},2000);
		   		               }else {
		   		            		toastr.warning("入库失败！");
		   		               }
		   		            }
		   		        });
	    			}
	        	}
    		break;
		}
	});
	 $("#export").click(function(){
		 var keyword = $("#cid").val();
			var selectState = $("#selectState").val();
			if(keyword == "" && selectState == ""){
				var strWhere = "r.isSimple = 1 and ";
			}else {
				if (keyword == "") {
					var strWhere = "r.isSimple = 1 and state = "+selectState+" and ";
				}else if (selectState == "") {
					var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and ";
				}else {
					var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and state = "+selectState+" and ";
				}
			}
			var receiveNumber = $.trim($("#receiveNumberc").val());
			if(receiveNumber != null && receiveNumber != ""){
				var strWhere = strWhere + " receive_number = '"+receiveNumber+"' and ";
			}
			var sendNumber = $.trim($("#khnum").val());
			if(sendNumber != null && sendNumber != ""){
				var strWhere = strWhere + " send_number = '"+sendNumber+"' and ";
			}
			var startTime = $.trim($("#startTime").val());
			if(startTime != null && startTime != ""){
				var strWhere = strWhere + " create_date >= '"+startTime+"' and ";
			}
			var endTime = $.trim($("#endTime").val());
			if(endTime != null && endTime != ""){
				var strWhere = strWhere + " create_date <= '"+endTime+"' and ";
			}

		    window.location.href='${pageContext.request.contextPath}/simplificationIn/doExportall.do?strWhere='+strWhere;
        })
	//选择供应商选中id查询该供应商的所有物料
    form.on('select(sendCompany)', function(data){
        var customer_id = data.value;
        $.ajax({
            type:'post',
            data:'id='+customer_id,
            url:'${pageContext.request.contextPath}/others/customerByName.do',
            dataType: 'JSON',
            async: false,
            success:function (json) {
                if(null != json){
                    $("#sendName").val(json.contacts_name)
                }
            }
        });
        table.reload('materiel_list',{
            data : new Array()
        });
    });
	//监听行工具事件
	table.on('tool(materiel_list)', function(obj){
		var data = obj.data;
		var oldData = table.cache["materiel_list"];
		if(obj.event === 'del'){
		  layer.confirm('确定删除吗？', function(index){
		  	oldData.pop(data);
		  	table.reload('materiel_list',{
                data : oldData
            });
		  	layer.close(index);
		  });
		}
	});
	/**
     * 表单校验
     */
    form.verify({
    	//value：表单的值、item：表单的DOM对象
    	sendCompany: function(value, item){
    		if(value == ''){
    			return '供应商不能为空';
    		}
    	},
    	createDate: function(value, item){
    		if(value == ''){
    			return '日期不能为空';
    		}
    	}
    });
    /**
     * 添加弹框中，选择物料后，点提交，带回的操作
     */
    form.on('submit(productform)', function (data) {
        var flag;
        var oldData = table.cache["materiel_list"];
        var checkStatus = table.checkStatus('contenttable2')
        //选中的物料
        var data = checkStatus.data;
        for (var j = 0; j < data.length; j++) {
            for (var k = 0; k < oldData.length; k++) {
                if (oldData[k].id == data[j].id) {
                    flag = 0;
                }
            }
        }
        if (flag != 0) {
            for (var i = 0; i < data.length; i++) {
                oldData.push(data[i]);
            }
        } else {
            toastr.warning("记录已经存在，不能重复添加");
        }
        table.reload('materiel_list',{
            data : oldData
        });
        $('[lay-id="materiel_list"] [data-edit="text"]:first').click();
        layer.close(productIndex)
    });
    /**
     * 通用表单提交(AJAX方式)（新增）
     */
    form.on('submit(addform)', function (data) {
    	$("#subform").attr("disabled",true);
    	var receiveNumber = $("#receiveNumber").val();
    	var oldData = table.cache["materiel_list"];
    	var data = oldData.filter(function(item){
            return item.totalNum == "" || item.totalNum == null || item.totalNum == undefined;
        })
    	if(oldData.length == 0){
    		toastr.warning("请选择物料！");
    		$("#subform").attr("disabled",false);
    	}/* else if(data.length > 0){
            toastr.warning("请输入正确的批次号");
    		$("#subform").attr("disabled",false);
        } */else{
        	//新增入库单
    		$.ajax({
    			type:'post'
    			,url:'${pageContext.request.contextPath }/simplificationIn/insertSimplificationIn.do'
    			,data:$('#addform').serialize()
    			,success:function(res){
    				if(res>0){
    					for (var i = 0; i < oldData.length; i++) {
    	                    var id = oldData[i].id;
    	                    var mid = oldData[i].id;
    	                    var totalNum = oldData[i].totalNum;
    	                    var ngNum = oldData[i].ngNum;
    	                    var pici = oldData[i].pici;
    	                    //添加收货明细
    	                    $.ajax({
    	                        url: '${pageContext.request.contextPath}/simplificationIn/insertDetails.do' ,
    	                        type: 'post',
    	                        data: {receiveNumber:receiveNumber, mid:mid, totalNum:totalNum,ngNum:ngNum,pici:pici},
    	                        async: false,
    	                        dataType:'JSON',
    	                        success: function (result) {
    	                            if (result > 0) {
    	                            	 toastr.success('新增成功');
                                         setTimeout(function(){
                                        	 layer.closeAll();
                                        	 var keyword = $("#cid").val();

                             				var selectState = $("#selectState").val();


                             				if(keyword == "" && selectState == ""){
                             					var strWhere = "r.isSimple = 1 and ";
                             				}else {

                             					if (keyword == "") {

                             						var strWhere = "r.isSimple = 1 and state = "+selectState+" and ";
                             					}else if (selectState == "") {

                             						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and ";
                             					}else {
                             						var strWhere = "r.isSimple = 1 and c.id = "+keyword+" and state = "+selectState+" and ";
                             					}


                             				}
                             				
                             				var receiveNumber = $.trim($("#receiveNumberc").val());
                             				if(receiveNumber != null && receiveNumber != ""){
                             					var strWhere = strWhere + " receive_number = '"+receiveNumber+"' and ";
                             				}
                             				var sendNumber = $.trim($("#khnum").val());
                             				if(sendNumber != null && sendNumber != ""){
                             					var strWhere = strWhere + " send_number = '"+sendNumber+"' and ";
                             				}
                             				var startTime = $.trim($("#startTime").val());
                             				if(startTime != null && startTime != ""){
                             					var strWhere = strWhere + " create_date >= '"+startTime+"' and ";
                             				}
                             				var endTime = $.trim($("#endTime").val());
                             				if(endTime != null && endTime != ""){
                             					var strWhere = strWhere + " create_date <= '"+endTime+"' and ";
                             				}

                             				table.reload('contenttable',{
                             					method:'get',
                             					where:{"strWhere": strWhere}
                             					,page: {
                             	                    curr: 1//重新从第 1 页开始
                             	                }
                             				});
                                         },1000);
    	                            }else{
    	                                toastr.warning("对不起，明细添加失败！");
    	                                $("#subform").attr("disabled",false);
    	                            }
    	                        },
    	                        error: function (data) {
    	                            toastr.error("对不起，明细添加错误！");
    	                            $("#subform").attr("disabled",false);
    	                        }
    	                    })
    	                }
    				}else{
    					toastr.error("对不起，入库单新增失败！");
    					$("#subform").attr("disabled",false);
    				}
    			}
    		})
    	}
    	var id= $("#id").val();
	})
});
function changeDateFormat(timestamp) {
	if (timestamp == '') {
		return '';
	} else {
		var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
		Y = date.getFullYear() + '-';
		M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
		D = (date.getDate()+1 < 10 ? '0'+(date.getDate()) : date.getDate())+ '      ';
		H = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours())+ ':';
        MI= (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())+':';
        S = (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
			
			return Y+M+D+H+MI+S;
	
	}
}
function curentTime() {
	  var now=new Date();
    var year=now.getFullYear(); 
	     var month=now.getMonth()+1; 
	     var date=now.getDate(); 
	     var hour=now.getHours(); 
	     var minute=now.getMinutes(); 
	     var second=now.getSeconds(); 
	     if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (date >= 0 && date <= 9) {
	       date = "0" + date;
	    } 
	   if (hour >= 1 && hour <= 9) {
		  hour = "0" + hour;
	    }
	  if (minute >= 1 && minute <= 9) {
		 minute = "0" + minute;
	    }
	 if (second >= 1 && second <= 9) {
		second = "0" + second;
	    }
	var time =year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 

   return time;
}
function curentTime1(d) {
	  var now=d;
  var year=now.getFullYear(); 
	     var month=now.getMonth()+1; 
	     var date=now.getDate(); 
	     var hour=now.getHours(); 
	     var minute=now.getMinutes(); 
	     var second=now.getSeconds(); 
	     if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (date >= 0 && date <= 9) {
	       date = "0" + date;
	    } 
	   if (hour >= 1 && hour <= 9) {
		  hour = "0" + hour;
	    }
	  if (minute >= 1 && minute <= 9) {
		 minute = "0" + minute;
	    }
	 if (second >= 1 && second <= 9) {
		second = "0" + second;
	    }
	var time =year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 

 return time;
}
function addProduct(){
	layui.use(['table','layer','upload','form'], function(){
		var table = layui.table;
		var layer = layui.layer,
	    form = layui.form
		var $ = layui.jquery
	    if ($("#sendCompany").val() == "") {
	        //toastr.warning("请选择供应商！");
	        layer.msg("请选择供应商！");
		} else {
	        productIndex = layer.open({
	            type: 1 					//Page层类型
	            ,area: ['900px', '450px'] 	//宽  高
	            ,title: '物料清单'
	            ,shade: 0.6 				//遮罩透明度
	            ,maxmin: true 				//允许全屏最小化
	            ,anim: 1 					//0-6的动画形式，-1不开启
	            ,content: $('#productDiv')
	            ,end: function () {
	                var formDiv = document.getElementById('productDiv');
	                formDiv.style.display = '';
	            }
	            ,success: function () {
	                var customer_id = $("#cid").val();
	                table.render({
	                    elem: '#productTable'
	                    //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?customer_id='+customer_id
	                    ,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customer_id+'&source=1'
	                    //,limits:[10,20,30]
	                    ,limit:10000
	                    ,id :'contenttable2'
	                    ,defaultToolbar:['filter', 'print']
	                    ,request: {   //如果无需自定义请求参数，可不加该参数
	                        pageName: 'page' //页码的参数名称，默认：page
	                        ,limitName: 'limit' //每页数据量的参数名，默认：limit
	                    }
	                    ,cols: [
	                        [{
	                            type: 'checkbox',
	                            fixed: 'left'
	                        }, {
	                            field:'id',
	                            title:'序号',
	                            sort: true,
	                            width: 60,
	                            type:'numbers',
	                            align:'center'
	                        }, {
	                            field: 'id',
	                            title: 'id',
	                            hide:true
	                        } , {
	                            field: 'customer_name',
	                            title: '供应商名称',
	                            align:'center',
	                        }, {
	                            field: 'materiel_name',
	                            title: '中文名称',
	                            align:'center',
	                        }, {
	                            field: 'materiel_num',
	                            title: 'SAP/PAD',
	                            align:'center',
	                        }, {
	                            field: 'outgoing_frequency',
	                            title: '出库频率',
	                            align:'center',
	                        }, 
	                        {
	                            field: 'pici',
	                            title: '批次',
	                            align:'center',
	                        },{
	                            field: 'packing_quantity',
	                            title: '包装数量',
	                            align:'center',
	                        }
	                        ]
	                    ]
	                    ,page: false
	                });

	                /* **********键盘Enter事件*********** */
                    $(document).keydown(function (event) {
                        if (event.keyCode == 13) { //绑定回车
                        	var materiel_name=$('#materiel_name').val();
                    		var materiel_num=$('#materiel_num').val();
                    		var table = layui.table;
                	 		var verify = /^[0-9,-]*$/;
                			//if(verify.test(materiel_num)){
                				var split = materiel_num.split(',')
                				if(split.length <= 5){
                					table.reload('contenttable2',{
                						method:'post'
                						,where:{"materielName":materiel_name,"materielNum":materiel_num}
                		         		/* ,page: {
                		                    curr: 1//重新从第 1 页开始
                		                } */
                					});
                				}else{
                					layer.msg("最多可同时查5个！");
                				}
                			/* }else{
                				layer.msg("只能输入数字和英文逗号！");
                			} */
                            return false;
                        };
                    });
                    /* **********Enter事件*********** */
	            }
	        });
		}
	});
}
var formatDate = function (date) {  
    var y = date.getFullYear();  
    var m = date.getMonth() + 1;  
    m = m < 10 ? '0' + m : m;  
    var d = date.getDate();  
    d = d < 10 ? ('0' + d) : d;  
    return y + '-' + m + '-' + d;  
};  
toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上
</script>

</body>
</html>